package cn.tedu.springbootdemo.controller;

import cn.tedu.springbootdemo.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
//@Controller  //用于配合组件扫描 创建控制器对象
//@ResponseBody //表明控制器方法的返回值绑定到HTTP响应体
@RestController  //@RestController =@Controller+@ResponseBody
@RequestMapping("/demo") //请求映射：使用该注解来映射请求到控制器方法
public class DemoController {

    Logger logger = LoggerFactory.getLogger(DemoController.class);
    //用户发起：http://localhost:8080/demo/hello    返回值：Hello World
    @GetMapping("/hello")
    public String hello(){
        logger.debug("Call hello()");
        return "Hello World!";
    }
   // @RequestMapping("/getUser")
    //@ResponseBody //作用是将javaBean转换成浏览器所能解析的json数据
    public User getUser(){
        User user=new User(1,"zhang","123","ADMIN");
        return user;
    }

    /**
     * @RequestParam注解的作用：请求参数名称与控制器中声明的形参的参数名不一致时，
     * 需要借助@RequestParam实现数据的映射
     */
   //需求：接收用户发起get，进行登录操作，并且有登录的参数需要接收
    //http://localhost:8080/demo/getParam?username=zhang&password=123456&aaa=ADMIN
    //@RequestMapping(method = RequestMethod.GET)=@GetMapping
//    @RequestMapping(method = RequestMethod.GET,value = "/getParam")
    @GetMapping("/getParam")
    public String getParam(String username,String password,@RequestParam("aaa") String roles){
        System.out.println(username+password+roles);
        return "get ok";
    }
//    @ResponseStatus(HttpStatus.CREATED) 设定HTTP响应状态码
    @PostMapping("/postParam")
    //@RequestParam("aaa")  :将请求参数映射到控制器的方法参数上
    //@RequestHeader("aaa") :映射请求头到控制器方法参数上
    public String postParam( String username ,String password,@RequestParam("aaa") String roles){
        System.out.println(username+password+roles);
        return "post ok";
    }
    //需求：基于请求路径中所传的用户的id，然后动态的查询用户的信息
    //http://localhost:8080/demo/getUser/1
    @GetMapping("/getUser/{id}")
    public User getUserById(@PathVariable Integer id){
        System.out.println(id);
        return new User(1,"zhang","123","ADMIN");
    }
    //@RequestBody将json转换成java对象
    @PostMapping("/register")
    public String register(@RequestBody User user){
        System.out.println(user.getUsername());
        return "register ok";
    }

}
